//
//  com_tskiViewController.m
//  08grouped
//
//  Created by Rocky Xu on 12-8-21.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "com_tskiViewController.h"
#import "NSDictionary-MutableDeepCopy.h"

@implementation com_tskiViewController
@synthesize names;
@synthesize keys;
@synthesize search;
@synthesize table;
@synthesize allNames;

-(void)handleSearchForTerm:(NSString *)searchTerm{
    NSMutableArray *sectionToRemove = [[NSMutableArray alloc] init];
    [self resetSearch];
    for(NSString *key in self.keys){
        NSMutableArray *array = [names mutableArrayValueForKey:key];
        NSMutableArray *toRemove = [[NSMutableArray alloc] init];
        for(NSString *name in array){
           // NSLog(@"NSNotFound: %i",NSNotFound);
            if([name rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound)
                [toRemove addObject:name];
        
        }
        if([array count] == [toRemove count])
            [sectionToRemove addObject:key];
        [array  removeObjectsInArray:toRemove];
        [toRemove release];
    }
    [self.keys removeObjectsInArray:sectionToRemove];
    [sectionToRemove release];
    [table reloadData];
        
}

-(void)resetSearch{
    NSMutableDictionary *allNamesCopy = [self.allNames mutableDeepCopy];
    self.names = allNamesCopy;
    //   self.names = [self.allNames mutableDeepCopy];
    [allNamesCopy release];
    NSMutableArray *keyArray = [[NSMutableArray alloc] init];
    [keyArray addObject:UITableViewIndexSearch];
    [keyArray addObjectsFromArray:[[self.allNames allKeys] sortedArrayUsingSelector:@selector(compare:)]];
    self.keys = keyArray;
    [keyArray release];

}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    NSString *path =[[NSBundle mainBundle]pathForResource:@"sortednames" ofType:@"plist"];
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
    
//    self.names = dict;
    self.allNames = dict;
    [dict release];
    NSLog(@"self.allNames %i",[[allNames allKeys] count]);
//    NSArray *array = [[names allKeys]sortedArrayUsingSelector:@selector(compare:)];
//    self.keys = array;
    //[array release];
    [self resetSearch];
    [table reloadData];
    [table setContentOffset:CGPointMake(0.0, 0.0) animated:YES];
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    self.names = nil;
    self.keys=nil;
    self.allNames=nil;
    self.table=nil;
    self.search=nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void)dealloc{
    [names release];
    [keys release];
    [table release];
    [search release];
    [allNames release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return [keys count];
    return ([keys count] > 0)?[keys count]:1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if([keys count] == 0)
        return 0;
    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];
    return [nameSection count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];
    
    NSString *key = [keys objectAtIndex:section];
    NSArray *nameArray = [self.names objectForKey:key];
    NSString *name = [nameArray objectAtIndex:row];
    static NSString *sectionsTableId = @"STI";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:sectionsTableId];
    if(cell == nil){
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sectionsTableId]autorelease];
    }
    cell.textLabel.text = name;
    return cell;
}

-(NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if([keys count] == 0)
        return nil;
    NSString *key = [keys objectAtIndex:section];
    if(key == UITableViewIndexSearch)
               return nil;
    return key;
}

-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    NSString *key =[keys objectAtIndex:index];
    if(key == UITableViewIndexSearch){
        [tableView setContentOffset:CGPointZero animated:YES];
        return NSNotFound;
    }
    else
        return index;
        
        
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"selected row~~~~~~~");
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    if(isSearching)
        return  nil;

    return keys;
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    isSearching = YES;
    [table reloadData];
}

-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [search resignFirstResponder];
        isSearching =NO;
    //search.text = @"";
    [tableView reloadData];
    return indexPath;
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSString *searchTerm = [searchBar text];
    [self handleSearchForTerm:searchTerm];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if([searchText length] == 0){
        [self resetSearch];
        [table reloadData];
        return;
    }
        [self handleSearchForTerm:searchText];
}
        
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    isSearching =NO;
    search.text = @"";
    [self resetSearch];
    [table reloadData];
    [searchBar resignFirstResponder];
}


@end
